const fs = require("fs");
const mode = require("../../model/development/codeGengeration.MODEL");
const { createSearch, createColumns, createConfigIndex, createEditForm, createAction, createApi, createIndex, createNodejsModel } = require("./gengeration");
const { IP, PROTOCOL, PORT, staticURL, assetsDir } = require("../../config");
const path = require("path");
const archiver = require('archiver');
/**
 * 这是一个获取搜索配置的函数。它会遍历输入的对象，将除了"id"、"createTime"和"updateTime"以外的所有键值对转化为一个包含label和value属性的对象，并将这些对象添加到一个数组中返回。
 *
 * @param {Object} modelData - 需要处理的对象，其键值对将被转化为包含label和value属性的对象并添加到数组中。
 * @return {Array} 返回一个数组，数组中的每个元素都是一个对象，该对象包含两个属性：label和value，它们的值都来自于输入对象的键值对。
 */
const getSearchConfig = (modelData) => {
    let searchConfig = [];
    modelData.forEach(item => {
        const { show, searchValueType, search, edit, require, unity, dataType, filed, desc } = item;
        let obj = {
            name: filed,
            label: desc,
            TYPE: searchValueType
        };
        searchConfig.push(obj)
    })
    return searchConfig;
}

const getColumnsConfig = (modelData) => {
    let columnsConfig = [];
    modelData.forEach(item => {
        const { show, searchValueType, search, edit, require, unity, dataType, filed, desc } = item;
        let obj = {};
        obj.title = desc;
        obj.key = filed;
        obj.dataIndex = filed;
        // show === true && columnsConfig.push(obj)
        columnsConfig.push(obj)
    })
    console.log("处理columns配置", columnsConfig)
    return columnsConfig;
}



const saveFile = async ({
    searchFieldsTemplate = String,
    indexTemplate = String,
    columnsPannelTemplate = String,
    actionTemplate = String,
    apiTemplate = String,
    configIndexTemplate = String,
    EditFormTemplate = String,
    nodejsModelTemplate = String,
}) => {
    await fs.writeFileSync(path.resolve(__dirname, '../../template/src/page/config/searchPanel.js'), searchFieldsTemplate)
    await fs.writeFileSync(path.resolve(__dirname, '../../template/src/page/config/columns.js'), columnsPannelTemplate)
    await fs.writeFileSync(path.resolve(__dirname, "../../template/src/page/config/actionPanel.js"), actionTemplate)
    await fs.writeFileSync(path.resolve(__dirname, "../../template/src/page/config/index.js"), configIndexTemplate)
    await fs.writeFileSync(path.resolve(__dirname, "../../template/src/page/index.jsx"), indexTemplate)
    await fs.writeFileSync(path.resolve(__dirname, "../../template/src/page/editForm.jsx"), EditFormTemplate)
    await fs.writeFileSync(path.resolve(__dirname, "../../template/src/api/api.js"), apiTemplate)
    await fs.writeFileSync(path.resolve(__dirname, "../../template/nodejs/model/model.js"), nodejsModelTemplate)
}


function zipDirectory(source, out) {
    const archive = archiver('zip', { zlib: { level: 9 } }); // 设置压缩级别
    const stream = fs.createWriteStream(out);

    return new Promise((resolve, reject) => {
        archive
            .directory(source, false) // 添加目录到归档，第二个参数为是否包括根目录
            .on('error', err => reject(err))
            .pipe(stream);

        stream.on('close', () => resolve());
        archive.finalize();
    });
}


//gengerationCode 生成代码并返回
const generationCode = async ({ id }, callBack = false) => {
    try {
        const res = await mode.findOne({ id }).lean().exec();
        if (res) {
            const { id, title, remark, componentName, reamrk, modelData, tableName } = res;
            const searchConfig = getSearchConfig(modelData);
            const columnsConfig = getColumnsConfig(modelData);
            const searchFieldsTemplate = createSearch({ searchConfig, pageTitle: title });
            const columnsPannelTemplate = createColumns({ columnsConfig, pageTitle: title });
            const actionTemplate = createAction({ pageTitle: title, componentName });
            const configIndexTemplate = createConfigIndex({ pageTitle: title, componentName })
            const apiTemplate = createApi({ pageTitle: title, componentName })
            const indexTemplate = createIndex({ pageTitle: title, componentName })
            const EditFormTemplate = createEditForm({ pageTitle: title, componentName })
            const nodejsModelTemplate = createNodejsModel({ pageTitle: title, componentName, tableName, modelData })
            await saveFile({
                searchFieldsTemplate: searchFieldsTemplate,
                columnsPannelTemplate: columnsPannelTemplate,
                actionTemplate: actionTemplate,
                indexTemplate: indexTemplate,
                apiTemplate: apiTemplate,
                configIndexTemplate: configIndexTemplate,
                EditFormTemplate: EditFormTemplate,
                nodejsModelTemplate: nodejsModelTemplate,
            })

        } else {
            return {
                code: '0001',
                msg: "生成失败"
            }
        }
    } catch (error) {
        console.log("error错误：", error)
    }
}


module.exports = {
    saveFile,
    generationCode,
    getSearchConfig,
    getColumnsConfig,
    zipDirectory
}